<?php
/**
 * Created by PhpStorm.
 * User: 84462
 * Date: 2015/7/9
 * Time: 16:09
 */
function AccessToken()
{
//    json_decode(file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".C('APPID')."&secret=".C('APPSECRET').""))->access_token;
//    S($cachename,$cache,3600);
    if (!S('access_token')) {
        $access_token = json_decode(file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . C('APPID') . "&secret=" . C('APPSECRET') . ""))->access_token;
        S('access_token', $access_token, 7100);
        return S('access_token');
    } else {
        return S('access_token');
    }
}

function JsapiTicket()
{
    $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" . AccessToken() . "&type=jsapi";
    if (!S('jsapi_ticket')) {
        $jsapi_ticket = json_decode(file_get_contents($url))->ticket;
        S('jsapi_ticket', $jsapi_ticket, 7100);
        return S('jsapi_ticket');
    } else {
        return S('jsapi_ticket');
    }
}

function GetUrl()
{
    $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
    $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
    $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self . (isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : $path_info);
    return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relate_url;
}

function wxNonceStr($length = 16, $type = FALSE)
{
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    if ($type == TRUE) {
        return strtoupper(md5(time() . $str));
    } else {
        return $str;
    }
}

function JsSign()
{
    if (!S('noncestr')) {
        S('noncestr', wxNonceStr(), 7100);
        $nonce = S('noncestr');
    } else {
        $nonce = S('noncestr');
    }
//    $nonce = S('noncestr');
    $time = time();
    $arr = array(
        'noncestr' => $nonce,
        'jsapi_ticket' => JsapiTicket(),
        'timestamp' => $time,
        'url' => GetUrl()
    );
    ksort($arr);
    $str1 = '';
    foreach ($arr as $k => $v) {
        $str1 .= $k . '=' . $v . '&';
    }
    $buff = trim($str1, "&");
    $str2 = sha1($buff);
    return array(
        'nonce' => $arr['noncestr'],
        'time' => $arr['timestamp'],
//        'sign' => $buff
        'sign' => $str2
    );
}

function cn($str)
{
    return strip_tags(mb_substr($str, "0", "1380", "utf-8"));
}

/**
 * @param $arr  从数据库取出的二位数组
 * @param $sort 需要排序的字段，可以是数组，亦可以是字符串，字符串认为是一个字段规则,为数组时，键越小的排序优先级越大
 * @param 本函数只提供按照给定字段的大小比对排序
 */
function ArrList($arr, $sort)
{
    $list = '';
    if (is_array($sort)) {
        foreach ($arr as $k => $v) {
            for ($i = 0; $i <= count($sort); $i++) {
                if ($arr[$k][$sort[$i]] > $arr[$k][$sort[$i] + 1]) {
                    $list[$k] = $arr[$k];
                } else {
                    $list[$k + 1] = $arr[$k];
                }
            }
        }
    } else {
        array_multisort($arr, SORT_DESC);
    }
    return $list;
}

/**
 * @param $data  方法只属于ueditor图片上传使用
 */
///^((?!http://).)*$/
function UeditorImageUploadCom($content)
{
    preg_match_all('/<img.*?src="\/Uploads(.*?)".*?>/is', $content, $array);
    $result = $array;
    $Image = new \Think\Image();
    foreach ($result[1] as $k => $v) {
        $Image->open('./Uploads' . $v);
        $Image->thumb(400, 400)->save('./Uploads' . $v);
    }
    return $result;
}

function GetUserInfo($openid)
{
    $AccessToken = AccessToken();
    $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $AccessToken . "&openid=" . $openid . "";
    return file_get_contents($url);
}

/**
 * @param $redirect_uri
 * @param int $state
 * @param string $scope
 */
function getCode($redirect_uri, $appid, $state = 1, $scope = 'snsapi_base')
{
    if ($redirect_uri[0] == '/') {
        $redirect_uri = substr($redirect_uri, 1);
    }
    //授权后重定向的回调链接地址，请使用urlencode对链接进行处理
    $redirect_uri = urlencode($redirect_uri);
    //返回类型，请填写code
    $response_type = 'code';
    //构造请求微信接口的URL
    $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='
        . $appid . '&redirect_uri=' . $redirect_uri . '&response_type='
        . $response_type . '&scope=' . $scope . '&state=' . $state . '#wechat_redirect';
    header('Location: ' . $url, true, 301);
}

/**
 * @param $arr
 */
function KeepSign($arr)
{
    for ($i = 1; $i <= count($arr); $i++) {
        if (($arr[$i]['sign_time'] - $arr[$i + 1]['sign_time']) > 86400) {
            return $i + 1;
        }
    }
}

/**
 * @param $x
 * @param $y
 */
function GetLocation($x, $y)
{
    $ApiUrl = "http://api.map.baidu.com/geocoder?location=" . $x . "," . $y . "&output=json";
    $json = file_get_contents($ApiUrl);
    $data = json_decode($json);
    return $data->result->addressComponent;
}

function xml_to_array($xml)
{
    $reg = "/<(\\w+)[^>]*?>([\\x00-\\xFF]*?)<\\/\\1>/";
    if (preg_match_all($reg, $xml, $matches)) {
        $count = count($matches[0]);
        $arr = array();
        for ($i = 0; $i < $count; $i++) {
            $key = $matches[1][$i];
            $val = xml_to_array($matches[2][$i]);  // 递归
            if (array_key_exists($key, $arr)) {
                if (is_array($arr[$key])) {
                    if (!array_key_exists(0, $arr[$key])) {
                        $arr[$key] = array($arr[$key]);
                    }
                } else {
                    $arr[$key] = array($arr[$key]);
                }
                $arr[$key][] = $val;
            } else {
                $arr[$key] = $val;
            }
        }
        return $arr;
    } else {
        return $xml;
    }
}